<template>
  <div class="pager-container">
    <a
      :class="{ disabled: current == 1 }"
      @click="handlerClick(1)"
    >|&lt;&lt;</a>
    <a
      :class="{ disabled: current == 1 }"
      @click="handlerClick(current - 1)"
    >&lt;&lt;</a>
    <a
      v-for="(n, i) in getPageNumbers"
      :key=i
      :class="{active: n == current}"
      @click="handlerClick(n)"
    >{{ n }}</a>
    <a
      :class="{ disabled: current == pageNumber }"
      @click="handlerClick(current + 1)"
    >&gt;&gt;</a>
    <a
      :class="{ disabled: current == pageNumber }"
      @click="handlerClick(pageNumber)"
    >&gt;&gt;|</a>
  </div>
</template>

<script>
export default {
  props: {
    // 总数据条数
    total: {
      type: Number,
      required: true,
    },
    // 当前页码
    current: {
      type: Number,
      default: 1,
    },
    // 显示几个页码
    visibleNumber: {
      type: Number,
      default: 10,
    },
    // 一页几条数据
    limit: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      pagesList: [],
    };
  },
  computed: {
    // 一共几页
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    // 显示的最小页码
    visibleMin() {
      // 当前页码 - 显示数量/2
      let min = this.current - Math.floor(this.visibleNumber / 2);
      if (min <= 1) {
        min = 1;
      }
      return min;
    },
    // 显示的最大页码
    visibleMax() {
      // 最小页码 + 显示页码数 - 自身
      let max = this.visibleMin + this.visibleNumber - 1;
      if (max >= this.pageNumber) {
        max = this.pageNumber;
      }
      return max;
    },
    // 显示的页码数组
    getPageNumbers() {
      const arr = [];
      for (let i = this.visibleMin; i <= this.visibleMax; i++) {
        arr.push(i);
        console.log("i", i);
      }
      return arr;
    },
  },
  methods: {
    handlerClick(page) {
      if (page <= 1) {
        page = 1;
      }
      if (page >= this.pageNumber) {
        page = this.pageNumber;
      }
      if (page == this.current) return;
      // 子组件抛出自定义事件，父组件注册子组件事件做处理
      this.$emit("changePage", page);
    },
  },
};
</script>

<style lang="less" scoped>
@import "~@/style/var.less";
.pager-container {
  display: flex;
  justify-content: center;
  margin: 10px 0;
  a {
    margin: 0 10px;
    cursor: pointer;
    color: @link;
    text-align: center;
    &.active {
      color: @blodWord;
      font-weight: bold;
      cursor: text;
    }
    &.disabled {
      color: @lightWord;
      cursor: not-allowed;
    }
  }
}
</style>